package ee.ut.cs.mc.mad.a72041.hw1;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.widget.EditText;

public class CycleOfLife extends Activity {

    private static final String DB = "db";
    private static final String DB_TABLE = "fields";
    private static final String DB_FIELD_ID = "id";
    private static final String DB_FIELD_VALUE = "value";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        createState();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cycle_of_life);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_cycle_of_life, menu);
        return true;
    }

    @Override
    protected void onPause() {
        saveState();
        super.onPause();
    }

    @Override
    protected void onStart() {
        restoreState();
        super.onStart();
    }

    private void createState() {
        SQLiteDatabase db = openOrCreateDatabase(DB, MODE_PRIVATE, null);
        if (db.getVersion() > 0) {
            return;
        }
        db.beginTransaction();
        try {
            db.execSQL("CREATE TABLE IF NOT EXISTS " + DB_TABLE + " (" + DB_FIELD_ID + " INT NOT NULL, " + DB_FIELD_VALUE + " VARCHAR(50), PRIMARY KEY (" + DB_FIELD_ID + "))");
            db.setVersion(1);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }

    }

    private void saveState() {
        // Gather field values
        final ContentValues firstName = new ContentValues(2);
        firstName.put(DB_FIELD_ID, R.id.firstNameValue);
        firstName.put(DB_FIELD_VALUE, ((EditText) findViewById(R.id.firstNameValue)).getText().toString());
        final ContentValues lastName = new ContentValues(2);
        lastName.put(DB_FIELD_ID, R.id.lastNameValue);
        lastName.put(DB_FIELD_VALUE, ((EditText) findViewById(R.id.lastNameValue)).getText().toString());

        doWithDb(new Closure<SQLiteDatabase>() {
            @Override
            public void exec(SQLiteDatabase db) {
                db.insertWithOnConflict(DB_TABLE, null, firstName, SQLiteDatabase.CONFLICT_REPLACE);
                db.insertWithOnConflict(DB_TABLE, null, lastName, SQLiteDatabase.CONFLICT_REPLACE);

            }
        });
    }


    private void restoreState() {
        doWithDb(new Closure<SQLiteDatabase>() {

            @Override
            public void exec(SQLiteDatabase db) {
                // Retrieve values from DB and populate fields
                Cursor query = db.query(DB_TABLE, null, null, null, null, null, null);
                while (!query.isAfterLast()) {
                    if (query.moveToNext()) {
                        EditText editField = ((EditText) findViewById(query.getInt(query.getColumnIndex(DB_FIELD_ID))));
                        editField.setText(query.getString(query.getColumnIndex(DB_FIELD_VALUE)));
                    }
                }
            }
        });
    }

    private void doWithDb(Closure<SQLiteDatabase> closure) {
        // Insert them to the database
        SQLiteDatabase db = openOrCreateDatabase(DB, MODE_PRIVATE, null);
        try {
            db.beginTransaction();
            try {
                closure.exec(db);
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }
        } finally {
            db.close();
        }
    }
}
